<?php
namespace app\index\controller;
use think\Console;
use think\Controller;
use think\Db;
use think\Session;
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2017/10/30
 * Time: 14:25
 */
class Login extends Controller{

    //返回用户列表
    function selUser(){

        $result['code'] = 1;
        $result['msg'] = '';

        $limit = input('limit');
        $page = input('page');

        $start = ($page-1) * $limit;

        $data = Db::table('user')
            ->where('level','<>','0')
            ->limit($start,$limit)
            ->field('Id,username,level,times,date')
            ->select();
        $data1 = Db::table('user')->where('level','<>','0')->select();

        if($data){
            $result['msg'] = '查询成功';
            $result['data'] = $data;
            $result['count'] = sizeof($data1);

        }
        else{
            $result['code'] = 0;
            $result['msg'] = '无数据';
        }
        return json($result);
    }

    //添加用户
    function addUser(){

        $result['code'] = 1;
        $result['msg'] = '';

        $username = input('username');
        $password = input('password');
        $level = input('level');

        if(strlen($username) < 3){
            $result['code'] = 0;
            $result['msg'] = '用户名长度不能小于3';
            return json($result);
        }
        elseif (strlen($password) < 5){
            $result['code'] = 0;
            $result['msg'] = '密码长度不能小于5';
            return json($result);
        }
        //检测用户是否注册过
        $user = Db::table('user')->where('username',$username)->find();
        if($user){
            $result['code'] = 0;
            $result['msg'] = '该用户已经添加';
            return json($result);
        }
        $data = ['username'=>$username,'password'=>$password, 'level'=>$level];
        //插入用户信息
        $user = Db::table('user')->insert($data);

        if($user){
            $result['code'] = 1;
            $result['msg'] = '添加用户成功';
            return json($result);
        }
        else{
            $result['code'] = 0;
            $result['msg'] = '插入数据库失败';
            return json($result);
        }

    }

    //删除用户
    function delUser(){

        $result['code'] = 1;
        $result['msg'] = '';

        $username = input('username');

        $data = Db::table('user')->where('username','=',$username)->delete();

        if($data){
            $result['msg'] = '删除成功';
            return json($result);
        }
        else{
            $result['code'] = 0;
            $result['msg'] = '删除失败';
            return json($result);
        }

    }

    //修改管理员密码
    function updateUser(){

        $user = Session::get('user');
        $update['password'] = input('password');
        $data = Db::table('user')->where('username','=',$user->name)->setField('password',input('password'));

        if($data){
            $this->success('修改成功');
        }
        else{
            $this->error('修改失败');
        }

    }

}